<template>
  <section class="todoapp">
    <HmHeader @addList="addList"></HmHeader>
    <HmBody 
    :list="readerList" 
    @changeFlag="changeFlag"
     @delList="delList"
     @allTrue="allTrue"
     ></HmBody>
    <HmFooter
      :sum="sum"
      :showTime="showTime"
      @ClearAll="ClearAll"
      :type="type"
      @changeType="changeType"
    ></HmFooter>
  </section>
</template>

<script>
// 引入
import HmHeader from './components/HmHeader.vue'
import HmBody from './components/HmBody.vue'
import HmFooter from './components/HmFooter.vue'

export default {
  // 监听list
  watch:{
    list:{
      deep:true,
      immediate:true,
      handler(newVal){
        localStorage.setItem('list',JSON.stringify(newVal))
      }
    }
  },

  // 注册
  components: {
    HmHeader,
    HmBody,
    HmFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')) || [
        { id: 1, flag: true, name: '读万卷书' },
        { id: 2, flag: false, name: '行万里路' },
      ],
      type: 'all',
    }
  },
  methods: {

    // 全选中
    allTrue(){
      this.list.forEach(item=>item.flag = true)
    },


    // 添加
    addList(name) {
      this.list = [...this.list, { id: +new Date(), flag: false, name }]
    },

    // 改flag
    changeFlag(id, flag) {
      this.list.forEach((item) => {
        if (item.id === id) {
          item.flag = flag
        }
      })
    },

    // 删除
    delList(id) {
      // 未完成不给删除
      if (this.list.find((item) => item.id === id).flag === false)
        return alert('未完成你确定要删除吗？')
      this.list = this.list.filter((item) => item.id !== id)
    },

    //清除已完成
    ClearAll() {
      this.list = this.list.filter((item) => !item.flag)
    },

    // 改变type值
    changeType(num) {
      this.type = num
    },
  },

  // 计算未完成的数量
  computed: {
    sum() {
      return this.list.filter((item) => !item.flag).length
    },
    showTime() {
      return this.list.some((item) => item.flag)
    },

    // 不同的type值传输不同的list
    readerList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },
  },
}
</script>

<style></style>
